const fs = require("fs-extra");
const path = require("path");
const jetpack = require("fs-jetpack");
// https://www.npmjs.com/package/fs-extra
// https://www.npmjs.com/package/fs-jetpack

let json = ''
let mdJson = {}
const BSET_URL = './docs/'
const ERROR_ARR = []
const RESULT_ARR = []

async function init () {
    // 读取配置文件
    readMdJson()
    let docsArr = await fs.readdir(path.join(__dirname, '/docs'))
    // 排除文件夹
    docsArr = exclude(docsArr, '.vitepress', 'index.md', 'public', "record.vue")
    // 赋予默认值
    json = `let slider = {\n`
    let judgeIndex = docsArr.length
    // 判断文件夹
    docsArr.forEach(async (target, index) => {
        try {
            let folder = fs.readdirSync(path.join(__dirname, `/docs/${target}`))
            // 生成json
            if (folder) {
                generateJson(folder, target)
                generateIndexMd(folder, target)
                RESULT_ARR.push(target + ' slider')
            }
            if (index === judgeIndex - 1) {
                // 赋予默认值
                json += `}`
                // 删除原先文件
                jetpack.remove("./slider.js")
                // 生成新文件
                await createFile('slider.js', json)
                RESULT_ARR.forEach(res => log('blue', `Generate: ${res} 创建成功.`))
                ERROR_ARR.forEach(err => log('red', `Fail: ${err} 是一个文件.`))
            }
        } catch (error) {
            let filename = String(error.path).match(/[^\\]+$/g)
            log('red', `Fail: ${filename} 是一个文件.`)
        }
    })
}

// 排除数组中的字段
function exclude (arr, ...regs) {
    regs.forEach(name => {
        let delIndex = arr.findIndex(v => v === name)
        if (delIndex != -1) {
            arr.splice(delIndex, 1)
        }
    })
    return arr
}

// 删除字符串中不需要的字段
function delStr (str, ...regs) { }

// 输出携带颜色的控制台信息
function log (color, text) {
    // https://www.51sjk.com/b194b134992/
    // 这里已经有造好的轮子了：chalk
    let styles = {
        'bold': '\x1B[1m%s',
        'italic': '\x1B[3m%s',
        'underline': '\x1B[4m%s',
        'inverse': '\x1B[7m%s',
        'strikethrough': '\x1B[9m%s',
        'white': '\x1B[37m%s',
        'grey': '\x1B[90m%s',
        'black': '\x1B[30m%s',
        'blue': '\x1B[34m%s',
        'cyan': '\x1B[36m%s',
        'green': '\x1B[32m%s',
        'magenta': '\x1B[35m%s',
        'red': '\x1B[31m%s',
        'yellow': '\x1B[33m%s',
        'whiteBG': '\x1B[47m%s',
        'greyBG': '\x1B[9;5;8m%s',
        'blackBG': '\x1B[40m%s',
        'blueBG': '\x1B[44m%s',
        'cyanBG': '\x1B[46m%s',
        'greenBG': '\x1B[42m%s',
        'magentaBG': '\x1B[45m%s',
        'redBG': '\x1B[41m%s',
    };
    let rgb = styles[color] || styles['yellow']
    console.log(rgb + '\x1B[0m', text);
}

// 生成对应 json 字符串
function generateJson (folder, folderName) {
    // 排除不需要
    exclude(folder, 'assets', 'index.md')
    // 生成items
    let itemStr = ''
    folder.forEach(filename => {
        let len = filename.length
        itemStr += `                    { text: '${filename.substring(0, len - 3)}', link: '/${folderName}/${filename}' },\n`
    })
    // 生成
    let str = `    '/${folderName}/': [
        {
            text: '${folderName}',
            items: [
${itemStr}
            ],
            collapsible: true
        }
    ],
`
    json += str
}

// 生成对应 index.md 文件
function generateIndexMd (folder, folderName) {
    try {
        // 不存在配置，不生成
        let mdObj = mdJson[folderName]
        if (!mdObj) return
        // 设置模板
        let template = `# ${mdObj.title || folderName}\n\n${mdObj.start || '需要了解的内容有✨：'}\n`
        // 设置链接
        for (const i in folder) {
            let value = folder[i]
            let len = value.length
            let url = `/${folderName}/${value}`
            template += `${i * 1 + 1}.  [${value.substring(0, len - 3)}](${url})\n`
        }
        // 创建文件
        let path = `${BSET_URL}${folderName}/index.md`
        // 删除内部文件
        if (process.argv[2] === '--del') {
            jetpack.remove(path)
        }
        if (fs.pathExistsSync(path)) {
            path = `${BSET_URL}${folderName}/${getRandomNumber(8)}-index.md`
            fs.appendFileSync(path, template)
            RESULT_ARR.push(path)
        } else {
            fs.appendFileSync(path, template)
            RESULT_ARR.push(path)
        }
    } catch (error) {
        log('red', `${folderName}/index.md 文件生成失败.`)
    }
}

// 创建文件
function createFile (name, content) {
    return new Promise(function (resolve, reject) {
        fs.appendFile(name, content, err => {
            err && reject(err)
            resolve('append success')
        });
    })
}

// 读取配置 md 文件
function readMdJson () {
    try {
        mdJson = fs.readJsonSync('./indexMd.json')
    } catch (err) {
        log('red', '无 indexMd.json 文件, index.md 不会生成')
    }
}

// 生成随机码
function getRandomNumber (num) {
    let str = ''
    for (let i = 0; i < num; i++) {
        str += Math.random().toFixed(1).substring(2)
    }
    return str
}

init()